from pymysql import connect

class chaxun():
    __conn = None
    __cursor = None

    @classmethod
    def __conn_set(cls):
        if cls.__conn is None:
            cls.__conn = connect(user="root",
                        password="root",
                        host="localhost",
                        database="books",
                        port=3306 )
            return cls.__conn
    @classmethod
    def __cursor_set(cls):
        if cls.__cursor is None:
            cls.__cursor = cls.__conn_set().cursor()
            return cls.__cursor
    @classmethod
    def chaxunsql(cls,sql):
        try:
            cursor = cls.__cursor_set()
            cursor.execute(sql)
            if sql.split()[0]=="select":
                return cursor.fetchall()
            else:
                cls.__conn.commit()
                return cursor.rowcount
        except Exception as e:
            cls.__conn.rollback()
        finally:
            cls.__cursor_clo()
            cls.__conn_clo()

    @classmethod
    def __cursor_clo(cls):
        if cls.__cursor:
            cls.__cursor.close()
            cls.__cursor = None

    @classmethod
    def __conn_clo(cls):
        if cls.__conn:
           cls.__conn.close()
           cls.__conn = None